<template>
  <div class="search-container">
        <!-- 标题栏 -->
    <van-nav-bar 
        left-arrow  
        @click-left="$router.back()" 
        class="page-nav-bar" 
        right-text="搜索" 
        fixed
        @click-right="toSearch()"
        >
            <van-search 
                slot="title"
                v-model="searchValue"
                placeholder="请输入搜索关键词"
                input-align="left"
                @search="toSearch"
                @focus="isResultsShow=false"
            />
    </van-nav-bar>
    <!-- 搜索结果 -->
    <div v-if="isResultsShow" class="search-result">
        <!-- 新闻列表 -->
        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :error.sync="loadingError"
            error-text="请求失败，点击重新加载"
            @load="onSearch"
        >
            <articleDetail
                v-for="(item,index) in searchResultList"
                :key="index"
                :cover="item.cover"
                :pubdate="item.pubdate"
                :aut_name="item.aut_name | filterAutherName"
                :comm_count="item.comm_count"
                :id="item.art_id"
            >
            <span v-html="TextHighlight(item.title)" slot="title">

            </span>
        </articleDetail>
        </van-list>
    </div>

    <!-- 搜索联想关键词 -->
    <div v-else-if="searchValue!==''" class="search-suggestion">
            <van-cell
                v-for="(item,index) in searchSuggestionList"
                class="search-history-item" 
                :key="index"
                @click="suggestion(item)"
            >
                <span slot="title" v-html="TextHighlight(item)"></span>
            <van-icon name="search" slot="icon"/>
        </van-cell>
    </div>

    <!-- 历史记录 -->
    <div class="history-item-box" v-else>
        <van-cell class="search-history" title="历史记录">
            <van-icon @click.stop="deleteAllHistory" name="delete-o" slot="right-icon"><span class="clear-text">清除全部</span></van-icon>
        </van-cell>
            <van-cell 
                class="search-history-item" 
                :title=item
                v-for="(item,index) in searchHistoryList"
                :key="index"
                @click.stop="suggestion(item)"
            >
                <span slot="right-icon">
                    <van-icon @click.stop="deleteSearchHistory(index)" name="close" />
                </span>
            </van-cell>

    </div>

  </div>
</template>

<script>
import articleDetail from '@/views/layout/PageHome/articleDetail.vue'
import {getSearchSuggestion,getSearchResult} from '@/api/user'
import { Toast,Dialog } from 'vant'
import {debounce} from 'lodash'
import { getItem,setItem  } from '@/utils/localStorage'//
import { SEARCH_HISTORY } from '@/utils/assets_text'
export default {
    data () {
        return {
            searchValue:'',
            isResultsShow:false,
            searchSuggestionList:[],
            page:1,
            searchResultList:[],
            loading:false,
            finished:false,
            loadingError:false,
            per_page:10,
            searchHistoryList:getItem(SEARCH_HISTORY) || [],
        }
    },
    components:{
        articleDetail,
    },
    methods:{
        filterAutherName(name){
            if (name==='黑马程序员(改不了)') {
                return '林子技术栈'
            }
        },
        async onSearch(){
            if (this.searchValue==='') {
                Toast('请输入搜索内容')
                return
            }
            // this.isResultsShow = true
            try {
                const {data} = await getSearchResult({
                    page:this.page,
                    per_page:this.per_page,
                    q:this.searchValue,
                })
                this.searchResultList.push(...data.data.results) 
                // console.log(this.searchResultList);
                if (data.data.results.length < this.per_page) {
                    this.finished=true
                }else{
                    this.page++
                    this.loading=false
                }
            } catch (err) {
                console.log(err)
                Toast('登陆过期!')
                this.loadingError=true
            }
        },
        async searchSuggestion(val){
            try {
            await getSearchSuggestion(val).then(res=>{
                this.searchSuggestionList=res.data.data.options
            })
            } catch (err) {
                console.log(err);
            }
        },
        TextHighlight(text){
            if (text && this.searchValue) {
                const reg = new RegExp(this.searchValue,'gi')
                return text.replace(reg,`<span style="color:#22cc9f;">${this.searchValue}</span>`,1)
            }
        },
        suggestion(text){
            this.searchValue = text
            setTimeout(()=>{
                this.toSearch()
            },101)
        },
        toSearch(){
            if (this.searchValue) {
                this.isResultsShow=true
                if (this.searchHistoryList.findIndex(item=>item===this.searchValue)===-1) {
                    this.searchHistoryList.unshift(this.searchValue)
                }else{
                    this.searchHistoryList.splice(this.searchHistoryList.findIndex(item=>item===this.searchValue),1)
                    this.searchHistoryList.unshift(this.searchValue)
                }
            }else{
                Toast('搜索内容为空!')
            }
        },
        deleteSearchHistory(index){
            this.searchHistoryList.splice(index,1)
        },
        deleteAllHistory(){
            if (this.searchHistoryList.length) {
                Dialog.confirm({
                title: '确认清除所有记录吗?',
                })
                .then(() => {
                    this.searchHistoryList=[]
                })
                .catch(() => {
                    
                });
            }else{
                Toast('没有历史记录')
            }
        }
    },
    watch:{
        searchValue:{
            handler:debounce(function(newVal){
                if (newVal!=='') {
                    this.searchSuggestion(newVal)
                    this.searchResultList=[]
                    this.page=1
                    this.finished=false
                    this.loading=false
                }
            },100),
            immediate:true,
            deep:true
        },
        searchHistoryList:{
            handler(){
                setItem(SEARCH_HISTORY,this.searchHistoryList)
            },
            immediate:true,
        },
    },
}
</script>

<style scoped lang="less">
.search-container{
    padding-top: 100px;
    box-sizing: border-box;
    width: 100%;
    height: 100vh;
    background-color: #fff;
    .van-search__content {
        border-radius: 4.05333rem;
    }
    ::v-deep .van-field__control{
        font-weight: normal;
        &::placeholder{
            font-weight: normal;
        }
    }
    ::v-deep .van-icon-search{
        color: #c8c9cc;
    }
    ::v-deep .van-nav-bar__title {
        max-width: 100%;
        width: 76%;
    }
    .van-icon-arrow-left{
        color: rgb(92, 92, 92);
    }
    ::v-deep .van-icon-clear{
        color: rgb(92, 92, 92);
    }
    .search-history{
        display: flex;
        align-items: center;
        .van-cell__title{
            font-size: 26px;
            color: #747474;
        }
        .van-icon-delete-o{
            display: flex;
            align-items: center;
            font-size: 30px;
            color: #969799;
            flex-direction: row-reverse;
            &:active{
                opacity: .7;
            }
            .clear-text{
                font-size: 26px;
            }
        }
    }
    .search-history-item{
        display: flex;
        align-items: center;
        .van-icon-close{
            font-size: 30px;
            color: #969799;
            &:active{
                opacity: .5;
            }
        }
        .van-icon-search{
            font-size: 30px;
            color: #969799;
            padding-right: 6px;
        }
        .van-cell__title{
            font-size: 26px;
            color: #2d2d2d;
        }
    }
    .history-item-box{
        max-height: 700px;
        overflow: hidden;
    }
}
</style>